package com.spx.core.services.security;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.ui.AbstractSourceProvider;
import org.eclipse.ui.ISources;

import com.spx.core.CoreActivator;
import com.spx.core.services.LoginListener;
import com.spx.core.types.User;

public class AuthoritySourceProvider extends AbstractSourceProvider  implements LoginListener
{

	public final static String LOGIN_STATE = "com.spx.core.user.loginState";
	public final static String PRESENT_USER = "com.spx.core.user.present";
	private final static String LOGGED_IN =   "loggedIn";
	private final static String LOGGED_OUT = "loggedOut";
	boolean loggedIn;

	@Override
	public String[] getProvidedSourceNames()
	{
		return new String[] { LOGIN_STATE,PRESENT_USER };
	}

	@Override
	public Map<String, String> getCurrentState()
	{
		String userName = getCurrentUserName();
		Map<String, String> currentState = new HashMap<String, String>(1);
		String loginState = loggedIn ? LOGGED_IN : LOGGED_OUT;
		
		currentState.put(PRESENT_USER, userName);
		currentState.put(LOGIN_STATE, loginState);
		return currentState;
	}

	private String getCurrentUserName()
	{
		String userName = "";
		User presentUser=	CoreActivator.getDefault().getSecurityService().getPresentUser();
		if (presentUser!=null){
			userName = presentUser.getName();
			System.out.println("PRESENT USER:"+userName);
		}
		return userName;
	}

	@Override
	public void dispose()
	{
	}


	public AuthoritySourceProvider(){
		CoreActivator.getDefault().getSecurityService().addLoginListener(this);
	}

	@Override
	public void loginActivity()
	{
		
		
		this.loggedIn = CoreActivator.getDefault().getSecurityService().getPresentUser() != null;;
		String currentState = loggedIn ? LOGGED_IN : LOGGED_OUT;
		fireSourceChanged(ISources.WORKBENCH, LOGIN_STATE, currentState);
		fireSourceChanged(ISources.WORKBENCH, PRESENT_USER, getCurrentUserName());

		
	}
	
	
	
}
